package com.cg.springSecurity.handler;

import com.cg.springSecurity.base.ResultInfo;
import com.cg.springSecurity.exception.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@ControllerAdvice
@RestController
public class ExceptionAdvice {

    //校验异常处理
    @ExceptionHandler(BindException.class)
    public ResultInfo<String> maxUploadSizeExceededException(BindException e) {
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        //修改mybatis-plus对tinyint的默认错误
        if (message.charAt(0) == 'F') {
            message = "参数只能为0或1";
        }
        return new ResultInfo<>(400, "error!",message);
    }

    //超出文件大小限制
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResultInfo<String> maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        e.printStackTrace();
        return new ResultInfo<>(401, e.getMessage(), "超出文件大小限制");
    }

    @ExceptionHandler(Exception.class)
    public ResultInfo<String> ExceptionHandler(Exception e) {
        e.printStackTrace();
        return new ResultInfo<>(501, "error!", null);
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResultInfo<String> ExceptionHandler(UsernameNotFoundException e) {
        e.printStackTrace();
        return new ResultInfo<>(400, "error!", e.getMessage());
    }
}
